import { LOGIN, LOGOUT, SET_USER_INFO } from '../constant';
import { login as loginApi, logout as logoutApi, getInfo as getUserInfoApi } from "../../api/login";
import { setToken,removeToken } from '../../utils/auth';

export const login = data => 
{   
    //console.log('====store=data===',data)
    const {username, password, code, uuid}  = data;
    //console.log('====store====',username, password, code, uuid)
    return async (dispatch) => {
        try {
            const response = await loginApi(username, password, code, uuid)
            if(response.code === 200){
                dispatch({ type: LOGIN, data: {token:response.token}});
                setToken(response.token);
                return true;
            } else {
                return false;
            }
        } catch (error) {
            return false;
        }
        
    }
};


export const logout = () => {
    return async (dispatch) => {
        try {
            const response = await logoutApi();
            if(response.code === 200){
                dispatch({ type: LOGOUT});
                removeToken();
                return true;
            } else {
                return false;
            }
        } catch (error) {
            return false;
        }

    }
}

export const getUserInfo = () => {
    return async (dispatch) => {
        try {
            const response = await getUserInfoApi();
            const {code, msg, permissions, roles, user} = response;
            if(response.code === 200){
                console.log('====store=response.data===',response.data)
                dispatch({ type: SET_USER_INFO, data: {permissions, roles, user}});
                return true;
            } else {
                return false;
            }
        } catch (error) {
            return false;
        }

    }
}